﻿Imports ATS.UI.Process
Imports ATS.Business.Entities
Imports System.ComponentModel
Imports System.ServiceModel
Imports System.Collections.Specialized
Imports System.Threading

Public Class CategoryWindow
    Private WithEvents _backgroundWorker As BackgroundWorker
    Private WithEvents _backgroundWorker_Page_Load As BackgroundWorker
    Private WithEvents _backgroundWorker_Save As BackgroundWorker
    Private WithEvents _backgroundWorker_CheckExisting As BackgroundWorker
    Public WithEvents oWindowList As OpenedWindowList = OpenedWindowList.GetList()
    Private WithEvents oWindow As OpenedWindowClass
    Private _upc As SubmitterUserProcess = Nothing
    Private _categoryDetail As Category = Nothing
    Private _categoryDetail_asynch As Category = Nothing
    Public WithEvents _categoryList As IObserveCategoryTable
    Private _categoryClassList As List(Of String) = Nothing
    Private _depreciationList As List(Of DepreciationClass) = Nothing


#Region "Control Events"
    Private Sub listBoxCategories_SelectionChanged(sender As Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles listBoxCategories.SelectionChanged
        If Not _categoryDetail Is Nothing Then
            If _categoryDetail.IsDirty Then
                If _
                    MessageBox.Show("Save entries before leaving?", "Save Data", MessageBoxButton.YesNo, _
                                     MessageBoxImage.Warning) = MessageBoxResult.Yes Then
                    SaveCategory()
                Else
                    If Not _categoryDetail.CategoryId = 0 Then

                        CancelEdit()
                    End If
                     
                End If
            End If
        End If
        LoadSelectedCategory()
    End Sub

    Private Sub comboBoxClass_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
    End Sub

    Private Sub ExpanderList_Expanded(sender As Object, e As System.Windows.RoutedEventArgs) Handles ExpanderList.Expanded
        busyAnimation.Visibility = Windows.Visibility.Visible

        'While _backgroundWorker_Page_Load.IsBusy
        '    Thread.Yield()
        '    System.Windows.Forms.Application.DoEvents()
        'End While

        If _categoryList Is Nothing Then
            _backgroundWorker = New BackgroundWorker
            _backgroundWorker.RunWorkerAsync()
        Else
            busyAnimation.Visibility = Windows.Visibility.Collapsed
        End If
    End Sub

    Private Sub searchBox_GotFocus(sender As Object, e As RoutedEventArgs) Handles searchBox.GotFocus
        If searchBox.Text.ToUpper.Contains("SEARCH") Then
            searchBox.Text = Nothing
        End If
    End Sub

    Private Sub searchBox_TextChanged(sender As Object, e As TextChangedEventArgs) Handles searchBox.TextChanged
        If Not listBoxCategories Is Nothing Then
            Dim icview As ICollectionView = CollectionViewSource.GetDefaultView(listBoxCategories.ItemsSource)
            icview.Filter = New Predicate(Of Object)(AddressOf FilterUserTable)
        End If
    End Sub

    Private Sub buttonNew_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles buttonNew.Click
        'ExpanderList.IsExpanded = True
        If Not _categoryDetail Is Nothing Then
            If _categoryDetail.IsDirty Then
                If _
                    MessageBox.Show("There are unsaved entries. Do you want to abandon your changes?", "Refresh", _
                                     MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.Yes Then
                    _categoryDetail.ResetDirtyBit()
                    SetWindowProperties(_categoryDetail.IsDirty)
                    NewItemCanvas.Visibility = Windows.Visibility.Visible
                    ucNewItem.ucLabel = "New Category Code"
                End If
            Else
                NewItemCanvas.Visibility = Windows.Visibility.Visible
                ucNewItem.ucLabel = "New Category Code"
            End If
        Else
            NewItemCanvas.Visibility = Windows.Visibility.Visible
            ucNewItem.ucLabel = "New Category Code"
        End If
    End Sub

    Private Sub buttonRefresh_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles buttonRefresh.Click
        If Not _categoryDetail Is Nothing Then
            If _categoryDetail.IsDirty Then
                If MessageBox.Show("There are unsaved entries. Do you really want to refresh the data?", "Refresh", _
                                     MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.Yes Then
                    If _categoryDetail.CategoryId = 0 Then
                        ClearAllControls()
                    Else
                        CancelEdit()
                    End If
                End If
            End If
        End If
    End Sub

    Private Sub buttonSave_Click(sender As Object, e As RoutedEventArgs) Handles buttonSave.Click
        If Not _categoryDetail Is Nothing Then
            If _categoryDetail.IsDirty Then
                SaveCategory()
            End If
        End If
    End Sub
#End Region

#Region "Window Events"
    Private Sub CategoryWindow_Closing(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles Me.Closing
        If Not _categoryDetail Is Nothing Then
            If _categoryDetail.IsDirty Then
                If _
                    MessageBox.Show("There are unsaved entries. Do you really want to exit?", "Exit", _
                                     MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.No Then
                    e.Cancel = True
                    _categoryDetail.EndEdit()
                End If
            End If
        End If
    End Sub

    Private Sub CategoryWindow_Closed(sender As Object, e As EventArgs) Handles Me.Closed
        Dim ied As IEnumerable(Of OpenedWindowClass) = From d In oWindowList Where d.WindowID = Me.Name
        oWindowList.Remove(ied.First)
        If Application.Current.Windows.Count = 1 Then
            Application.Current.Windows(0).Activate()
        End If
    End Sub

    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.
        _upc = New SubmitterUserProcess()
    End Sub

    Private Sub CategoryWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
        _backgroundWorker_Page_Load = New BackgroundWorker
        _backgroundWorker_Page_Load.RunWorkerAsync()
    End Sub
#End Region

#Region "Background Workers"
    ' This event handler is where the actual work is done.
    Private Sub _backgroundWorker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles _backgroundWorker.DoWork
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
        LoadCategories()
    End Sub

    Private Sub _backgroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles _backgroundWorker.RunWorkerCompleted
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)
        Else
            listBoxCategories.ItemsSource = _categoryList
            RefreshRecordCount()
            If _categoryList Is Nothing Then
                listBoxCategories.SelectedIndex = -1
            End If

        End If
        busyAnimation.Visibility = Windows.Visibility.Collapsed
    End Sub

    Private Sub _backgroundWorker_SaveDoWork( _
                                          ByVal sender As Object, _
                                          ByVal e As DoWorkEventArgs) _
        Handles _backgroundWorker_Save.DoWork
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)

        If e.Argument = "edit" Then
            _categoryDetail_asynch = _upc.UpdateCategoryRecord(_categoryDetail)
        ElseIf e.Argument = "new" Then
            _categoryDetail_asynch = _upc.CreateCategory(_categoryDetail)
        End If
    End Sub

    Private Sub _backgroundWorker_SaveRunWorkerCompleted( _
                                                      ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
        Handles _backgroundWorker_Save.RunWorkerCompleted
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)
        Else
            listBoxCategories.ItemsSource = _categoryList
            busyAnimationSaveAndDelete.Visibility = Windows.Visibility.Collapsed
            _categoryDetail = _categoryDetail_asynch
            _categoryDetail_asynch = Nothing
            _categoryDetail.ResetDirtyBit()
            SetWindowProperties(_categoryDetail.IsDirty)
        End If
    End Sub

    ' This event handler is where the actual work is done.
    Private Sub _backgroundWorker_Page_Load_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles _backgroundWorker_Page_Load.DoWork
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
        LoadClassList()
        LoadDepreciationList()
    End Sub

    Private Sub _backgroundWorker_Page_Load_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles _backgroundWorker_Page_Load.RunWorkerCompleted
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)
        Else
            comboboxClass.ItemsSource = _categoryClassList
            comboboxDepreciationMethod.ItemsSource = _depreciationList
            comboboxDepreciationMethod.DisplayMemberPath = "Depreciation"
            comboboxDepreciationMethod.SelectedValuePath = "DepreciationCode"

        End If
    End Sub

    Private Sub _backgroundWorker_ChckExistingUserDoWork( _
                                         ByVal sender As Object, _
                                         ByVal e As DoWorkEventArgs) _
       Handles _backgroundWorker_CheckExisting.DoWork
        Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
        e.Result = _upc.ReadCategory(e.Argument)
    End Sub

    Private Sub _backgroundWorker_ChckExistingRunWorkerCompleted( _
                                                      ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) _
        Handles _backgroundWorker_CheckExisting.RunWorkerCompleted
        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)
        Else
            If Not e.Result Is Nothing Then
                ucNewItem.LabelError.Content = "Category code already exist."
            Else
                listBoxCategories.SelectedIndex = -1
                _categoryDetail = New Category()
                Me.DataContext = _categoryDetail
                HookupChangeEventHandler(_categoryDetail)
                _categoryDetail.CategoryCode = ucNewItem.TextBoxNewUser.Text
                '_categoryDetail.CategoryName = String.Empty
                '_categoryDetail.IsActive = True
                '_categoryDetail.CategoryDesc = String.Empty
                '_categoryDetail.DepreciationMethod = 1
                '_categoryDetail.Years = 0
                '_categoryDetail.AssetClass = String.Empty

                textboxCode.Text = ucNewItem.TextBoxNewUser.Text
                NewItemCanvas.Visibility = Windows.Visibility.Collapsed
                mainOverlay.Visibility = Visibility.Collapsed
                Me.Title = _categoryDetail.CategoryCode
                SetWindowProperties(_categoryDetail.IsDirty)
            End If
        End If
        ucNewItem.busyAnimationNewUser_visibility = Windows.Visibility.Collapsed
    End Sub
#End Region

#Region "Support Procedures"
    Sub ClearAllControls()
        HelperClass.ClearCheckBox(gridCategoryDetails)
        HelperClass.ClearComboBox(gridCategoryDetails)
        HelperClass.ClearPasswordBox(gridCategoryDetails)
        HelperClass.ClearTextBox(gridCategoryDetails)
        Me.Title = "Category"
        _categoryDetail.ResetDirtyBit()
        SetWindowProperties(_categoryDetail.IsDirty)

    End Sub

    Private Sub CancelEdit()
        _categoryDetail.CancelEdit()
        _categoryDetail.ResetDirtyBit()
        SetWindowProperties(_categoryDetail.IsDirty)
    End Sub

    Private Sub LoadIObserveCategoryTable()

        For Each item In _upc.ReadAllCategories.OrderBy(Function(x) x.CategoryName)
            With item
                IObserveCategoryTable.list.Add(New Category(.CategoryId _
                                                            , .CategoryName _
                                                            , .CategoryCode _
                                                            , .CategoryDesc _
                                                            , .DepreciationMethod _
                                                            , .Years _
                                                            , .AssetClass _
                                                            , .IsActive))
            End With
        Next
    End Sub

    Sub sortData()
        Dim ied As IEnumerable(Of Category) = From d In _categoryList Order By d.CategoryName
        For Each i In ied
            _categoryList.Remove(i)
            _categoryList.Add(i)
        Next
    End Sub

    Private Sub SetWindowProperties(dirty As Boolean)
        If dirty Then
            Me.Title &= If(Not Me.Title.ToUpper.Contains("UNSAVED"), " (unsaved)", "")
        Else
            Me.Title = If(Title.ToUpper.Contains("UNSAVED"), Me.Title.Substring(0, Me.Title.Length - 10), Me.Title)
        End If

        For itemIndex = 0 To oWindowList.Count - 1
            If oWindowList(itemIndex).WindowID = Me.Name Then
                oWindowList(itemIndex).WindowName = Me.Title
                oWindowList(itemIndex).WindowIsDirty = dirty
            End If
        Next
    End Sub

    Sub LoadCategories()
        Try
            If IObserveCategoryTable.list.Count = 0 Then
                LoadIObserveCategoryTable()
            End If
            _categoryList = IObserveCategoryTable.list
        Catch ex As Exception
            MessageBox.Show(ex.Message & ControlChars.Lf & ex.ToString, "Error loading Category list", MessageBoxButton.OK, _
                             MessageBoxImage.[Error])
        End Try
    End Sub

    Private Sub LoadSelectedCategory()
        If listBoxCategories.SelectedIndex >= 0 Then
            _categoryDetail = listBoxCategories.SelectedItem
            Me.DataContext = _categoryDetail
            _categoryDetail.ResetDirtyBit()
            HookupChangeEventHandler(_categoryDetail)
            mainOverlay.Visibility = Visibility.Collapsed
            Me.Title = textboxCode.Text
            _categoryDetail.BeginEdit()
        Else
            _categoryDetail = Nothing
            Me.Title = "Category"
            mainOverlay.Visibility = Visibility.Visible
        End If
        If Not _categoryDetail Is Nothing Then
            SetWindowProperties(_categoryDetail.IsDirty)
        Else
            SetWindowProperties(False)
        End If
    End Sub

    Sub LoadClassList()
        _categoryClassList = _upc.GetAllCategoryClass()
    End Sub

    Sub LoadDepreciationList()
        _depreciationList = _upc.DepreciationList()
    End Sub

    Private Sub HookupChangeEventHandler(categoryDetail As Category)
        ' Add a PropertyChanged event handler for 
        ' the specified Customer instance:
        AddHandler categoryDetail.PropertyChanged, _
            AddressOf HandlePropertyChanged
    End Sub

    Private Sub HandlePropertyChanged(ByVal sender As Object, ByVal e As PropertyChangedEventArgs)
        If _categoryDetail.IsDirty Then
            SetWindowProperties(_categoryDetail.IsDirty)
        End If
    End Sub

    Private Sub RefreshRecordCount()
        If Not _categoryList Is Nothing Then
            If _categoryList.Count = 1 Then
                ExpanderText.Text = _categoryList.Count & " record found"
            Else
                ExpanderText.Text = _categoryList.Count & " records found"
            End If
        End If
    End Sub

    Private Sub TextBox_Error(sender As Object, e As ValidationErrorEventArgs)
        If e.Action = ValidationErrorEventAction.Added Then
            DirectCast(sender, Control).ToolTip = e.[Error].ErrorContent.ToString()
        Else
            DirectCast(sender, Control).ToolTip = ""
        End If
    End Sub

    Public Function FilterUserTable(ByVal t As Object) As Boolean
        Dim _Category As Category
        _Category = t
        Return _Category.CategoryName.ToUpper.Contains(searchBox.Text.ToUpper)
    End Function
    Private Sub Data_CollectionChanged( _
                                        ByVal sender As Object, _
                                        ByVal e As NotifyCollectionChangedEventArgs) _
        Handles _categoryList.CollectionChanged

        ' Did you add or remove an item in the collection?
        If e.Action = NotifyCollectionChangedAction.Add Or _
           e.Action = NotifyCollectionChangedAction.Remove Then
            RefreshRecordCount()
        End If
    End Sub

    'Sub SaveCategoryDetails()
    '    busyAnimationSaveAndDelete.Visibility = Windows.Visibility.Visible
    '    Try
    '        _backgroundWorker_Save = New BackgroundWorker
    '        If _categoryList.Where(Function(x) x.CategoryCode = textboxCode.Text).Count > 0 Then
    '            'edit
    '            _backgroundWorker_Save.RunWorkerAsync("edit")
    '        Else
    '            'new
    '            _backgroundWorker_Save.RunWorkerAsync("new")

    '            'update list
    '            _categoryList.Add(_categoryDetail)
    '            sortData()
    '            Dim ctr As Integer = 0
    '            For Each item In _categoryList
    '                If item.CategoryId = _categoryDetail.CategoryId Then
    '                    Exit For
    '                End If
    '                ctr += 1
    '            Next
    '            listBoxCategories.SelectedIndex = ctr
    '        End If
    '        SetWindowProperties(_categoryDetail.IsDirty)
    '        _backgroundWorker_Save.Dispose()


    '    Catch faultEx As FaultException
    '        MessageBox.Show(faultEx.Message, "Error Saving UserDetails", MessageBoxButton.OK, MessageBoxImage.[Error])
    '    Catch ex As Exception
    '        MessageBox.Show(ex.Message, "Error Saving UserDetails", MessageBoxButton.OK, MessageBoxImage.[Error])
    '    End Try

    'End Sub

    Sub SaveCategory()
        busyAnimationSaveAndDelete.Visibility = Windows.Visibility.Visible
        Try
            _backgroundWorker_Save = New BackgroundWorker
            Dim categoryExist As Boolean = False

            If Not _categoryList Is Nothing Then
                If _categoryList.Where(Function(x) x.CategoryCode = textboxCode.Text).Count > 0 Then
                    categoryExist = True
                End If
            End If

            If categoryExist Then
                'edit
                _backgroundWorker_Save.RunWorkerAsync("edit")
                _categoryDetail.ResetDirtyBit()
            Else
                'new
                _categoryDetail = New Category
                With _categoryDetail
                    .CategoryCode = If(textboxCode.Text.Length = 0, Nothing, textboxCode.Text)
                    .CategoryName = If(textboxName.Text.Length = 0, Nothing, textboxName.Text)
                    .IsActive = CheckBoxIsActive.IsChecked
                    .CategoryDesc = textboxDescription.Text
                    .DepreciationMethod = comboboxDepreciationMethod.SelectedItem.depreciationcode
                    .Years = If(IsNumeric(textboxLife.Text), textboxLife.Text, Nothing)
                    .AssetClass = comboboxClass.Text
                End With



                _backgroundWorker_Save.RunWorkerAsync("new")

                If Not _categoryList Is Nothing Then
                    'update list
                    _categoryList.Add(_categoryDetail)
                    sortData()
                    Dim ctr As Integer = 0
                    For Each item In _categoryList
                        If item.CategoryId = _categoryDetail.CategoryId Then
                            Exit For
                        End If
                        ctr += 1
                    Next
                    listBoxCategories.SelectedIndex = ctr
                End If
            End If
            _categoryDetail.ResetDirtyBit()
            SetWindowProperties(_categoryDetail.IsDirty)

            _backgroundWorker_Save.Dispose()
        Catch faultEx As FaultException
            MessageBox.Show(faultEx.Message, "Error Saving Category Details", MessageBoxButton.OK, MessageBoxImage.[Error])
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error Saving Category Details", MessageBoxButton.OK, MessageBoxImage.[Error])
        End Try
        busyAnimationSaveAndDelete.Visibility = Windows.Visibility.Collapsed
    End Sub
#End Region

#Region "User Control Events"

    Private Sub uc_OKButtonClicked(ByVal sender As Object, ByVal e As RoutedEventArgs) _
        Handles ucNewItem.OkButtonClicked
        ucNewItem.busyAnimationNewUser_visibility = Windows.Visibility.Visible
        _backgroundWorker_CheckExisting = New BackgroundWorker
        _backgroundWorker_CheckExisting.RunWorkerAsync(ucNewItem.TextBoxNewUser.Text)
        _backgroundWorker_CheckExisting.Dispose()
    End Sub

    Private Sub uc_CancelButtonClicked(ByVal sender As Object, ByVal e As RoutedEventArgs) _
        Handles ucNewItem.CancelButtonClicked
        NewItemCanvas.Visibility = Windows.Visibility.Collapsed
    End Sub

#End Region


End Class


